﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Manager{

    /// <summary>
    /// 加载远程文件管理 游戏更新文件时使用，需要文件地址以及加载完成之后需要放到什么目录
    /// </summary>
    public class DownLoadRemoteFileManager
    {
        private List<string> files;

        private Action<float> progressCallBack;

        private Action completeCallBack;

        private List<RemoteFileLoader> loaderList = new List<RemoteFileLoader>();

        public void LoadRemoteFile(List<string> _files, Action<float> _progressCallBack = null, Action _completeCallBack = null)
        {
            files = _files;
            progressCallBack = _progressCallBack;
            completeCallBack = _completeCallBack;
            loaderList.Clear();
            foreach (string filePath in files)
            {
                RemoteFileLoader loader = new RemoteFileLoader();
                loaderList.Add(loader);
                loader.LoadRemoteFile(filePath, OnLoadComplete, OnLoadError);
            }
        }

        private float progressValue
        {
            get
            {
                return (float)(files.Count - loaderList.Count) / (float)(files.Count);
            }
        }

        private void OnLoadComplete(RemoteFileLoader loader)
        {
            UpdateProgress(loader);
        }

        private void OnLoadError(RemoteFileLoader loader)
        {
            //LogManager.addLog();
            UpdateProgress(loader);
        }

        private void UpdateProgress(RemoteFileLoader loader)
        {
            loaderList.Remove(loader);
            if (progressCallBack != null)
                progressCallBack(progressValue);
            if (loaderList.Count == 0)
            {
                if (completeCallBack != null)
                    completeCallBack();
                Clear();
            }
        }

        public void Clear()
        {
            progressCallBack = null;
            completeCallBack = null;
            if(loaderList != null)
            {
                loaderList.Clear();
                loaderList = null;
            }
        }

    }
}
